<template>
  <view class="page_root" data-page-name="填报" data-page-identification="g_n0od6kf1vk">
    <!-- UNI_APP_EXEGESIS_START NAVIGATION_TEMPLATE UNI_APP_EXEGESIS_END -->
    <!-- begin vid_1xajtn371k 自定义模板_iqjjqf7218 -->
    <view class="body">
      <view class="content" v-if="state.canFilled">
        <view class="bgc-img"></view>
        <view class="main">
          <view class="score-content" v-if="state.msg">
            <view class="score-item-line">
              <view class="score-item-left">区域：</view>
              <view class="score-item-right">{{ state.msg.areaName }}</view>
            </view>
            <view class="score-item-line">
              <view class="score-item-left">项目：</view>
              <view class="score-item-right">{{ state.msg.projectName }}</view>
            </view>
            <view class="score-item-line">
              <view class="score-item-left">信息统计创建人：</view>
              <view class="score-item-right">{{ state.msg.createdBy }}</view>
            </view>
            <view class="score-item-line">
              <view class="score-item-left">信息统计创建时间：</view>
              <view class="score-item-right">{{ state.msg.createdTime }}</view>
            </view>
            <view class="score-item-line">
              <view class="score-item-left">计划完成时间：</view>
              <view class="score-item-right">{{ state.msg.planEndTime }}</view>
            </view>
          </view>
          <u-form :model="state.formModel" ref="recordForm" :rules="rules">
            <u-form-item
              v-for="(item, index) in state.dataSource"
              :key="index"
              required="true"
              label-position="top"
              :label="
                item.componentType === 'SELECT' && item.selectType === 'CHECK'
                  ? `${item.lableName}（多选）`
                  : item.lableName
              "
              :prop="item.columnName"
            >
              <!-- 输入 -->
              <u-input
                v-if="item.componentType === 'SIMPLE_INPUT'"
                border="true"
                v-model="state.formModel[item.columnName]"
                :maxlength="item.inputLimit"
                :placeholder="'最多可输入' + item.inputLimit + '个字符'"
              ></u-input>
              <!-- 输入 -->
              <!-- 多选 -->
              <u-checkbox-group
                v-if="item.componentType === 'SELECT' && item.selectType === 'CHECK'"
                v-model="state.formModel[item.columnName]"
              >
                <u-checkbox v-for="(item, index) in item.selectList" :key="index" :name="item">{{
                  item
                }}</u-checkbox>
              </u-checkbox-group>
              <!-- 多选 -->
              <!-- 单选 -->
              <u-radio-group
                v-if="item.componentType === 'SELECT' && item.selectType === 'RADIO'"
                v-model="state.formModel[item.columnName]"
              >
                <u-radio
                  shape="square"
                  @change="radioChange"
                  v-for="(item, index) in item.selectList"
                  :key="index"
                  :name="item"
                >
                  {{ item }}
                </u-radio>
              </u-radio-group>
              <!-- 单选 -->
              <!-- 日期 -->
              <u-calendar v-model="state.dateShow" mode="date" @change="dateChange"></u-calendar>
              <u-input
                v-if="item.componentType === 'DATE'"
                border="true"
                type="select"
                placeholder="请选择日期范围"
                v-model="state.formModel[item.columnName]"
                @click="showSlectDate(`${item.columnName}`)"
              ></u-input>
              <!-- 日期 -->
              <!-- 上传附件 -->
              <u-upload
                width="106px"
                height="106px"
                class="vid_rg51oa99zm"
                :action="vid_rg51oa99zm_props.action"
                v-if="item.componentType === 'FILE'"
                :uploadFile="vid_rg51oa99zm_props.uploadFile"
                :isShowFormatContent="vid_rg51oa99zm_props.isShowFormatContent"
                :listType="vid_rg51oa99zm_props.listType"
                :required="vid_rg51oa99zm_props.required"
                v-model:fileList="state.formModel[item.columnName]"
                :deletable="uploadDisabled"
                maximumFileSize="vid_rg51oa99zm_props.maximumFileSize"
                @uploadFailed="handle_vid_rg51oa99zm_uploadFailed"
                @uploadSuccess="handle_vid_rg51oa99zm_uploadSuccess"
                @removeSuccess="handle_vid_rg51oa99zm_uploadSuccess"
              >
              </u-upload>
              <!-- 上传附件 -->
            </u-form-item>
          </u-form>
        </view>
      </view>

      <view v-else class="over-tip">
        <u-alert-tips type="warning" title="" description="已超过填报时间！"></u-alert-tips>
      </view>
    </view>
    <view class="bottom-btn" v-if="state.canFilled">
      <u-button
        :disabled="completeDisabled"
        block
        type="primary"
        class="bc-btn"
        @click="handleCancel"
        >取消</u-button
      >
      <u-button
        :disabled="completeDisabled"
        block
        :loading="state.confirmLoading"
        type="primary"
        class="wc-btn"
        @click="handleComplete"
        >保存</u-button
      >
    </view>
    <!-- end vid_1xajtn371k 自定义模板_iqjjqf7218 -->
  </view>
</template>
  <script setup>
import {
  ref,
  reactive,
  toRaw,
  markRaw,
  watch,
  computed,
  onBeforeMount,
  onMounted,
  onBeforeUnmount,
  onUnmounted,
  onActivated,
  onDeactivated,
  getCurrentInstance,
} from 'vue';
import { useRoute } from 'vue-router';
const route = useRoute();
import { get, post, put, del, request, requestWithHeaders } from '@/utils/http/Axios';
// import { cloneDeep, localGet, traversalTreeStructure, set, checkCaseCondition, throttle, merge, debounce, getGridStyle, getCellRenderAble, formulaStrategy, getComponentParamsValue, get as lodashGet } from '@/utils/index';
// import { isEqual, isNullOrEmpty, isEmptyArr, isArray, isEmpty, isNullOrUnDef, isContained } from '@/utils/is';
// import { CovertOptions, getChartsDataSourceConvert } from '@/utils/chart';
// import { propertyFormatByNumber, propertyFormatByPercentage, propertyFormatByDate, parseSubFromDataList } from '@/utils/format';
// import { checkCommonCondition, getResultByCurrentCommonCondition } from '@/utils/formCondition';
// import { FormFormat } from '@/utils/formFormat'
import { customAddWaterMarkFunc, generateWaterMarkText } from '@/utils/addWaterMark';
// import dayjs from 'dayjs';
// import hashSum from 'hash-sum';
/*** UNI_APP_EXEGESIS ***
    import { handleRedirect, permission, parseJson } from '@/utils/common';
    import { onPullDownRefresh, onLoad, onReady, onShow, onHide, onPageScroll, onUnload } from '@dcloudio/uni-app';
    import { BroadcastMessage } from '@/utils/BroadcastMessage';
    import { sendToken } from "@/hooks/useIframeToken";
    *** UNI_APP_EXEGESIS ***/

// ---------------------------- 属性定义 ----------------------------
const sourceId = 'page3000000872';

// 获取传入的流程ID和组件参数
const props = defineProps({
  processInstanceId: {
    type: [String, Number, Boolean],
    default: undefined,
  },
  hideNav: {
    type: [Boolean],
    default: undefined,
  },
});

// 组件参数默认值
const componentParamsDefaultProps = {};

// 是否显示菜单按钮
const isMenuIconShow = false;
// NAVIGATION_MENU
const handleShowNavigation = () => {};

let isProcessState = ref(false);

const setTimeOutList = [];

const vid_1xajtn371k_props = reactive({
  code: '',
});

// ============================ 属性定义 ============================

// ---------------------------- 元素数据引用 ----------------------------
// 组件 自定义模板_iqjjqf7218 ref 的引用
const vid_1xajtn371k_ref = ref(null);
// 动态key的map
const fieldTypeMap = {};
// 动态key的map
const refMap = { vid_1xajtn371k_ref };

const showState = reactive({
  vid_1xajtn371k_visible: true,
});
// ============================ 元素数据引用 ============================

// ---------------------------- 数据 ----------------------------

// ============================ 数据 ============================

// ---------------------------- 方法 ----------------------------
// ---------------------------- 页面数据 ----------------------------

// ============================ 页面数据 ============================

// ---------------------------- 数据字典 ----------------------------

// ============================ 数据字典 ============================

// ---------------------------- 响应 ----------------------------

// ============================ 响应 ============================

// ---------------------------- 函数 ----------------------------

// 自定义函数 返回上一页
const customFunction_goBack_z5t6bmhb7z = (params) => {
  uni.navigateBack();
};

// ============================ 函数 ============================

// ---------------------------- 页面参数 ----------------------------

const pageParameter_state = reactive({
  processInstanceId: undefined,
});

// ============================ 页面参数 ============================

// ---------------------------- 组件事件处理方法 ----------------------------

// ============================ 组件事件处理方法 ============================

// ============================ 方法 ============================

// ---------------------------- 生命周期 ----------------------------
/*** UNI_APP_EXEGESIS ***
        // 获取上一层传递的数据
        const workflowChannel = new BroadcastMessage('WORKFLOW');
        workflowChannel.publish({ status: 'Ready' });
        workflowChannel.subscribe((data) => {
          if (data) {
            isProcessState.value = (window.self !== window.parent && data.type === 'hideHeader');
          }
        });
        *** UNI_APP_EXEGESIS ***/

const pageScrollTop = ref(0);

// *** PREVIEW_EXEGESIS ***
onMounted(() => {
  setPageParams(route.query);
  // 设置表单的rule
  try {
  } catch {
    // do nothing
  }
});
// *** PREVIEW_EXEGESIS *** //

/*** UNI_APP_EXEGESIS ***
    const routeOption = ref({})
    onLoad((option) => {
      routeOption.value = option;
    });
    onReady(() => {
      setPageParams(routeOption.value)
      // 设置表单的rule
      try{
  
      }catch{
          // do nothing
      }
    });
    // 图表刷新标记
    const uChartsReshowFlag = ref(false);
    onHide(() => { // 页面隐藏后标记置为false(如果不置为false无法触发图表更新)
        uChartsReshowFlag.value = false
    })
    onShow(() => {
        uChartsReshowFlag.value = true; // 页面激活后,标记置为true
  
        setPageParams(routeOption.value)
    })
    onPageScroll(e => {
        pageScrollTop.value = e.scrollTop
    });
    *** UNI_APP_EXEGESIS ***/

let setPageParams = (routerParam) => {
  const pageParams = [{ dataType: 'STRING', name: 'processInstanceId' }];
  const strategyMap = {
    STRING: (param, paramValue) => {
      pageParameter_state[param.name] = paramValue;
    },
    BOOLEAN: (param, paramValue) => {
      if ('true' === (paramValue || '').toLowerCase()) {
        pageParameter_state[param.name] = true;
      } else if ('false' === (paramValue || '').toLowerCase()) {
        pageParameter_state[param.name] = false;
      } else {
        // TODO: 是否要支持toast
        console.error('参数传入错误！类型不匹配！');
      }
    },
    NUMBER: (param, paramValue) => {
      if (!isNaN(paramValue)) {
        pageParameter_state[param.name] = Number(paramValue);
      } else {
        // TODO: 是否要支持toast
        console.error('参数传入错误！类型不匹配！');
      }
    },
    ARRAY: (param, paramValue) => {
      if (isNullOrUnDef(paramValue) || !paramValue || paramValue === 'undefined') {
        // default value
        pageParameter_state[param.name] = [];
      } else if (paramValue.trim().startsWith('[') && paramValue.trim().endsWith(']')) {
        try {
          pageParameter_state[param.name] = JSON.parse(decodeURI(paramValue));
        } catch (error) {
          console.error('参数解析失败 ', error);
        }
      } else {
        console.error('参数传入错误！类型不匹配！');
      }
    },
  };
  pageParams.forEach((param) => {
    strategyMap[param.dataType](param, routerParam[param.name]);
  });
};

onUnmounted(() => {
  // 销毁定时器
  setTimeOutList.forEach(({ repeat, timer }) => {
    repeat ? clearInterval(timer) : clearTimeout(timer);
  });
});

/*** UNI_APP_EXEGESIS ***
    onPullDownRefresh(() => {
      // 下拉刷新
      setTimeout(() => {
          uni.stopPullDownRefresh()
      }, 1000)
    })
    *** UNI_APP_EXEGESIS ***/

// ============================ 生命周期 ============================

// ---------------------------- 数据关联处理 ----------------------------
// ---------------------------- 组件数据同步 ----------------------------

// ============================ 组件数据同步 ============================
//
// ============================ 数据关联处理 ============================

// ---------------------- 不同组件自定义的处理逻辑 ---------------------

// ====================== 不同组件自定义的处理逻辑 ======================

// ================================定制化逻辑========================================
import dayjs from 'dayjs';
onMounted(() => {
  try {
    // recordForm?.value?.setRules(state.rules);
    let appDiv = document.querySelector('#app');
    appDiv.style.background = 'linear-gradient(180deg, #E1EFFD 100%, #ffffff 0%)';
    let topHeader = document.querySelector('.uni-page-head');
    if (topHeader) topHeader.remove();
    const queryString = window.location.search;

    // 使用 URLSearchParams 解析参数字符串
    const urlParams = new URLSearchParams(queryString);
    // 获取特定参数的值
    const id = urlParams.get('id');
    const userId = urlParams.get('userId');
    state.formId = id;
    state.userId = userId;
    console.log(userId);
    getData();
  } catch {
    // do nothing
  }
});
const state = reactive({
  formId: undefined,
  userId: undefined,
  canFilled: true,
  rules: {},
  msg: undefined,
  dateShow: false,
  dataSource: [],
  formModel: {},
  selectDate: undefined,
});
const recordForm = ref(null);
const vid_rg51oa99zm_props = reactive({
  name: 'file',
  action: '/file-storage/api/v1/file/upload',
  uploadFile: (data) =>
    request({
      url: '/file-storage/api/v1/file/upload',
      method: 'POST',
      responseType: 'blob',
      withCredentials: false,
      data,
      timeout: 360000,
      headers: { 'Content-Type': 'application/json' },
    }),
  customAddWaterMarkFunc: async (file) =>
    customAddWaterMarkFunc(file, await generateWaterMarkText()),
  isShowFormatContent: false,
  showQrcode: true,
  accept: 'image/*',
  multiple: true,
  listType: 'picture',
  showUploadList: true,
  required: false,
  qrcodeUrl: undefined,
  token: undefined,
  setTimeOutList: [],
  systemFileList: [],
  isSingle: false,
  isCamera: false,
  addWatermark: false,
  maximumFileSize: '',
  confirmLoading: false,
});

function getData() {
  get(
    `/solution-ppm/api/v2/built-in-system-ppm/data_collect/get_data_collector/${state.formId}`,
  ).then((data) => {
    if (data.code !== 200) {
      uni.showToast({
        title: data.message,
        icon: 'error',
      });
    }
    const planEndTimeObj = dayjs(data.data.planEndTime);  // 将 planEndTime 转换为 dayjs 对象
const currentTime = dayjs();  // 获取当前时间

// 判断当前时间是否晚于 planEndTime
if (planEndTimeObj.isBefore(currentTime, 'day')) {
  state.canFilled = false;  // 当前时间晚于 planEndTime，不能填写
} else {
  state.canFilled = true;  // 当前时间等于或早于 planEndTime，允许填写
}

    state.msg = data.data;
    state.dataSource = data.data.componentList;
    // 规则生成
    state.rules = state.dataSource.reduce((acc, item) => {
      acc[item.columnName] = [
        {
          required: true,
          message: `请完善${item.lableName}`,
          trigger: ['change', 'blur'],
          validator: (rule, value, callback) => {
            if (Array.isArray(value)) {
              // 如果是数组，校验数组是否为空
              if (value.length > 0) {
                callback(); // 校验通过
              } else {
                callback(new Error(`请至少选择一个${item.key}`)); // 校验失败
              }
            } else if (typeof value === 'string') {
              // 如果是字符串，校验字符串是否为空
              if (value.trim() !== '') {
                callback(); // 校验通过
              } else {
                callback(new Error(`请输入${item.key}`)); // 校验失败
              }
            } else {
              // 其他类型（如数字、对象等），按空值校验
              if (value) {
                callback(); // 校验通过
              } else {
                callback(new Error(`请完善${item.key}`)); // 校验失败
              }
            }
          },
        },
      ];
      return acc;
    }, {});
    recordForm?.value?.setRules(state.rules);
  });
}
function dateChange(e) {
  console.log(e);
  state.formModel[state.selectDate] = e.result;
}
function showSlectDate(name) {
  state.selectDate = name;
  state.dateShow = true;
}
function handle_vid_rg51oa99zm_uploadSuccess(e) {}
function handleComplete() {
  console.log(recordForm.value);
  recordForm?.value
    ?.validate()
    .then(() => {
      state.confirmLoading = true;
      console.log(state.formModel);
      const cleanedData = Object.fromEntries(
        Object.entries(state.formModel).filter(([key]) => key !== 'undefined'),
      );
      // 遍历对象，处理数组类型的数据并去掉undefined键
      const processedData = Object.keys(cleanedData).reduce((result, key) => {
        const value = cleanedData[key];

        // 如果值是 undefined 或者值为 null，跳过
        if (value === undefined || value === null) {
          return result;
        }
        // 如果值是 undefined 或者值为 null，跳过
        if (value === undefined || value === null) {
          return result;
        }
        // 如果值是数组，进一步判断类型
        if (Array.isArray(value)) {
          // 判断是否为文件数组（数组内元素包含特定字段）
          if (
            value.length > 0 &&
            value[0].hasOwnProperty('name') &&
            value[0].hasOwnProperty('size')
          ) {
            // 文件数组，转换为 JSON 字符串
            result[key] = JSON.stringify(value);
          } else {
            // 普通数组，转换为以逗号分隔的字符串
            result[key] = value.join(',');
          }
        } else {
          // 普通值，直接复制
          result[key] = value;
        }

        return result;
      }, {});
      post(
        `/solution-ppm/api/v2/built-in-system-ppm/data_collect/save_data_collector/${state.formId}/${state.userId}`,
        processedData,
      )
        .then((data) => {
          if (data.code !== 200) {
            uni.showToast({
              title: data.message,
              icon: 'error',
            });
            return;
          }
          uni.showToast({
            title: data.message,
            icon: 'success',
          });
        })
        .finally(() => {
          state.confirmLoading = false;
        });
    })
    .catch((errors) => {
      console.log('校验失败', errors);
    });
}
function handleCancel() {
  uni.showToast({
    title: '请手动关闭页面!',
    icon: 'none',
  });
}
watch(
  () => state.dataSource,
  () => {
    state.formModel = state.dataSource.reduce((acc, item) => {
      if (item.name === 'SELECT' || item.name === 'FILE') {
        acc[item.value] = []; // 初始化为数组
      } else {
        acc[item.value] = ''; // 初始化为空字符串
      }
      return acc;
    }, {});
  },
  { immediate: true },
);
</script>
  <style lang="less" scoped>
.page_root {
  min-height: 100%;
  box-sizing: border-box;
  overflow: auto;
}

.bottom-btn {
  display: flex;
  width: 100%;
  height: 52px;
  position: absolute;
  justify-content: space-between;
  bottom: -40px;
  left: 0;
  border-radius: 0;
  z-index: 20;
  font-size: 20px;
  font-weight: bold;
}

.bc-btn,
.wc-btn {
  width: 45%;
}
.body {
  padding: 15px;
  padding-top: 0;
  background-color: linear-gradient(180deg, #e1effd 100%, #ffffff 0%);
  height: calc(100vh - 50px);
  overflow: auto;
  position: relative;
}
.main {
  background: #ffffff;
  box-shadow: 0 0 10px 0 #cfe7ff;
  border-radius: 6px;
  padding: 0 15px;
  position: relative;
  top: 15px;
}

.score-item-line {
  width: 100%;
  height: 30px;
  display: flex;
}
.score-item-left {
  font-size: 14px;
  color: #595959;
  letter-spacing: 0;
  font-weight: 400;
  line-height: 30px;
}
.score-item-right {
  font-family: PingFangSC-Semibold;
  font-size: 14px;
  color: #262626;
  letter-spacing: 0;
  font-weight: 600;
  line-height: 30px;
}
.score-content {
  position: relative;
  top: 15px;
}
.bgc-img {
  position: absolute;
  width: 100%;
  height: 300px;
  left: 0;
  top: -248px;
  background-image: url('http://10.40.0.33:9001/file-storage/416680575854426112.png');
  background-size: cover;
}
.over-tip {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}
</style>
  